/*
 * Copyright (C) 2014 The Senzu Dev Team
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package gui;

import dto.EspecialidadDTO;
import dto.ObraSocialDTO;
import dto.ObraSocialPlanDTO;
import dto.TarifaDTO;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import logic.Especialidad;
import logic.ObraSocial;
import logic.ObraSocialPlan;
import logic.Tarifa;
import util.InputHelper;

/**
 *
 * @author lucifer
 */
public class ObraSocialPanel extends javax.swing.JPanel implements Slave {

  private Master master;

  public void SetMaster(Master master) {
    this.master = master;
  }

  public void SetModeActions() {
    ((JFrame) master).setTitle("Administración de Obras Sociales - Senzu");
  }

  public void ShowTarifasEspecialidades() {
    try {
      obraSocialjTableMouseClicked(null);
      jTabbedPane1.setSelectedIndex(2);
    } catch (Exception e) {
    }
  }

  private ArrayList<Integer> oIDs;
  private ArrayList<Integer> pIDs;

  private ArrayList<Integer> eIDs;
  private ArrayList<Integer> tIDs;

  private ObraSocial obraSocialSeleccionada;
  private ObraSocialPlan planSeleccionado;
  private Especialidad especialidadSeleccionada;

  public ObraSocialPanel(Master master) {
    SetMaster(master);

    initComponents();
    setContactoEditable(false);

    preObraSocialAndPlan();
  }

  private void preObraSocialAndPlan() {
    try {
      updateObraSocialTable(ObraSocial.All());
      try {
        obraSocialjTable.setRowSelectionInterval(0, 0);
        obraSocialSeleccionada = new ObraSocial(ObraSocial.SearchByID(oIDs.get(0)));
        jTabbedPane1.setEnabled(true);
      } catch (Exception e) {
      }

      updatePlanTable(obraSocialSeleccionada != null ? ObraSocialPlan.All(obraSocialSeleccionada.getId()) : new ArrayList<ObraSocialPlanDTO>());
      try {
        planjTable.setRowSelectionInterval(0, 0);
        planSeleccionado = new ObraSocialPlan(ObraSocialPlan.SearchByID(pIDs.get(0)));
      } catch (Exception e) {
      }

      preEspecialidad();
    } catch (SQLException e) {
      System.out.printf("?op:database connection failed\n");
    }
  }

  private void preEspecialidad() {
    try {
      updateEspecialidadTable(Especialidad.All());
      try {
        especialidadjTable.setRowSelectionInterval(0, 0);
        especialidadSeleccionada = new Especialidad(Especialidad.SearchByID(eIDs.get(0)));
      } catch (Exception e) {
      }
    } catch (SQLException e) {
      System.out.printf("?e:database connection failed\n");
    }
  }

  private void setContactoEmpty() {
    nombrejTextField.setText("Obra social no seleccionada");
    apellidojTextField.setText("Obra social no seleccionada");
    telefonojTextField.setText("Obra social no seleccionada");
    emailjTextField.setText("Obra social no seleccionada");
  }

  private void setContactoData() {
    nombrejTextField.setText(obraSocialSeleccionada.getContactoNombre());
    apellidojTextField.setText(obraSocialSeleccionada.getContactoApellido());
    telefonojTextField.setText(obraSocialSeleccionada.getContactoTelefono());
    emailjTextField.setText(obraSocialSeleccionada.getContactoEmail());
  }

  private void setContactoEditable(boolean b) {
    nombrejTextField.setEditable(b);
    apellidojTextField.setEditable(b);
    telefonojTextField.setEditable(b);
    emailjTextField.setEditable(b);
  }

  private void updateObraSocialTable(ArrayList<ObraSocialDTO> o) {
    DefaultTableModel m = new DefaultTableModel();
    m.addColumn("Nombre de la Obra Social");

    oIDs = new ArrayList<>();
    for (int i = 0; i < o.size(); i++) {
      oIDs.add(o.get(i).getId());
      m.addRow(new Object[] {o.get(i).getNombre()});
    }
    obraSocialjTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    obraSocialjTable.setModel(m);

    for (int i = 0; i < obraSocialjTable.getRowCount(); i++) {
      for (int j = 0; j < obraSocialjTable.getColumnCount(); j++) {
        obraSocialjTable.scrollRectToVisible(obraSocialjTable.getCellRect(i, j, true));
      }
    }

    jTabbedPane1.setEnabled(false);
  }

  private void updatePlanTable(ArrayList<ObraSocialPlanDTO> p) {
    DefaultTableModel m = new DefaultTableModel();
    m.addColumn(String.format("Planes Disponibles%s", obraSocialSeleccionada != null ? " para " + obraSocialSeleccionada.getNombre() : ""));

    pIDs = new ArrayList<>();
    for (int i = 0; i < p.size(); i++) {
      pIDs.add(p.get(i).getId());
      m.addRow(new Object[] {p.get(i).getNombre()});
    }
    planjTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    planjTable.setModel(m);

    for (int i = 0; i < planjTable.getRowCount(); i++) {
      for (int j = 0; j < planjTable.getColumnCount(); j++) {
        planjTable.scrollRectToVisible(planjTable.getCellRect(i, j, true));
      }
    }
  }

  private void updateEspecialidadTable(ArrayList<EspecialidadDTO> e) throws SQLException {
    if (obraSocialSeleccionada == null) {
      return;
    }

    DefaultTableModel m = new DefaultTableModel();
    m.addColumn("Especialidad");
    m.addColumn("Tarifa");

    eIDs = new ArrayList<>();
    tIDs = new ArrayList<>();
    TarifaDTO t;
    for (int i = 0; i < e.size(); i++) {
      eIDs.add(e.get(i).getId());
      tIDs.add((t = Tarifa.SearchByObraSocialEspecialidad(obraSocialSeleccionada.getId(), eIDs.get(i))).getId());
      m.addRow(
        new Object[] {
          e.get(i).getNombre(),
          String.format("%.2f", t.getPrecio())
        }
      );
    }
    especialidadjTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    especialidadjTable.setModel(m);

    DefaultTableCellRenderer left = new DefaultTableCellRenderer();
    left.setHorizontalAlignment(SwingConstants.LEFT);

    DefaultTableCellRenderer right = new DefaultTableCellRenderer();
    right.setHorizontalAlignment(SwingConstants.RIGHT);

    especialidadjTable.getColumnModel().getColumn(1).setCellRenderer(right);
    especialidadjTable.getColumnModel().getColumn(1).setMinWidth(96);
    especialidadjTable.getColumnModel().getColumn(1).setMaxWidth(112);
    especialidadjTable.getColumnModel().getColumn(0).setCellRenderer(left);

    for (int i = 0; i < planjTable.getRowCount(); i++) {
      for (int j = 0; j < planjTable.getColumnCount(); j++) {
        especialidadjTable.scrollRectToVisible(planjTable.getCellRect(i, j, true));
      }
    }

    especialidadjTable.getColumnModel().getColumn(0).setResizable(false);
    especialidadjTable.getColumnModel().getColumn(1).setResizable(false);
  }

  @SuppressWarnings("unchecked")
  // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
  private void initComponents() {

    jTabbedPane1 = new javax.swing.JTabbedPane();
    obraSocialAndPlanjPanel = new javax.swing.JPanel();
    planjScrollPane = new javax.swing.JScrollPane();
    planjTable = new JTable() {
      public boolean isCellEditable(int i, int j) {
        return false;
      }
    };
    obraSocialjScrollPane = new javax.swing.JScrollPane();
    obraSocialjTable = new JTable() {
      public boolean isCellEditable(int i, int j) {
        return false;
      }
    };
    addjButton = new javax.swing.JButton();
    planjTextField = new javax.swing.JTextField();
    deljButton1 = new javax.swing.JButton();
    addjButton1 = new javax.swing.JButton();
    obraSocialjTextField = new javax.swing.JTextField();
    deljButton = new javax.swing.JButton();
    contactojPanel = new javax.swing.JPanel();
    nombrejTextField = new javax.swing.JTextField();
    nombrejLabel = new javax.swing.JLabel();
    apellidojTextField = new javax.swing.JTextField();
    apellidojLabel = new javax.swing.JLabel();
    telefonojTextField = new javax.swing.JTextField();
    telefonojLabel = new javax.swing.JLabel();
    emailjTextField = new javax.swing.JTextField();
    emailjLabel = new javax.swing.JLabel();
    guardarContactojButton = new javax.swing.JButton();
    modificarContactojButton = new javax.swing.JButton();
    cancelarGuardarContactojButton = new javax.swing.JButton();
    tarifajPanel = new javax.swing.JPanel();
    addjButton2 = new javax.swing.JButton();
    especialidadjScrollPane = new javax.swing.JScrollPane();
    especialidadjTable = new JTable() {
      public boolean isCellEditable(int i, int j) {
        return j == 1;
      }
    };
    especialidadjTextField = new javax.swing.JTextField();
    deljButton2 = new javax.swing.JButton();
    actualizarTarifasjButton = new javax.swing.JButton();

    jTabbedPane1.addChangeListener(new javax.swing.event.ChangeListener() {
      public void stateChanged(javax.swing.event.ChangeEvent evt) {
        jTabbedPane1StateChanged(evt);
      }
    });

    planjTable.setModel(new javax.swing.table.DefaultTableModel(
      new Object [][] {

      },
      new String [] {
        "Planes Disponibles"
      }
    ) {
      Class[] types = new Class [] {
        java.lang.String.class
      };
      boolean[] canEdit = new boolean [] {
        false
      };

      public Class getColumnClass(int columnIndex) {
        return types [columnIndex];
      }

      public boolean isCellEditable(int rowIndex, int columnIndex) {
        return canEdit [columnIndex];
      }
    });
    planjTable.getTableHeader().setReorderingAllowed(false);
    planjTable.addMouseListener(new java.awt.event.MouseAdapter() {
      public void mouseClicked(java.awt.event.MouseEvent evt) {
        planjTableMouseClicked(evt);
      }
    });
    planjScrollPane.setViewportView(planjTable);
    if (planjTable.getColumnModel().getColumnCount() > 0) {
      planjTable.getColumnModel().getColumn(0).setResizable(false);
    }

    obraSocialjTable.setModel(new javax.swing.table.DefaultTableModel(
      new Object [][] {

      },
      new String [] {
        "Nombre de la Obra Social"
      }
    ) {
      Class[] types = new Class [] {
        java.lang.String.class
      };
      boolean[] canEdit = new boolean [] {
        false
      };

      public Class getColumnClass(int columnIndex) {
        return types [columnIndex];
      }

      public boolean isCellEditable(int rowIndex, int columnIndex) {
        return canEdit [columnIndex];
      }
    });
    obraSocialjTable.getTableHeader().setReorderingAllowed(false);
    obraSocialjTable.addMouseListener(new java.awt.event.MouseAdapter() {
      public void mouseClicked(java.awt.event.MouseEvent evt) {
        obraSocialjTableMouseClicked(evt);
      }
    });
    obraSocialjTable.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyReleased(java.awt.event.KeyEvent evt) {
        obraSocialjTableKeyReleased(evt);
      }
    });
    obraSocialjScrollPane.setViewportView(obraSocialjTable);
    if (obraSocialjTable.getColumnModel().getColumnCount() > 0) {
      obraSocialjTable.getColumnModel().getColumn(0).setResizable(false);
    }

    addjButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gui/add.png"))); // NOI18N
    addjButton.setMaximumSize(new java.awt.Dimension(44, 27));
    addjButton.setMinimumSize(new java.awt.Dimension(44, 27));
    addjButton.setPreferredSize(new java.awt.Dimension(44, 27));
    addjButton.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        addjButtonActionPerformed(evt);
      }
    });

    planjTextField.setText("Ingrese un plan");
    planjTextField.setMaximumSize(new java.awt.Dimension(205, 27));
    planjTextField.setMinimumSize(new java.awt.Dimension(205, 27));
    planjTextField.setPreferredSize(new java.awt.Dimension(205, 27));
    planjTextField.addFocusListener(new java.awt.event.FocusAdapter() {
      public void focusGained(java.awt.event.FocusEvent evt) {
        planjTextFieldFocusGained(evt);
      }
    });
    planjTextField.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        planjTextFieldActionPerformed(evt);
      }
    });

    deljButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gui/remove.png"))); // NOI18N
    deljButton1.setMaximumSize(new java.awt.Dimension(44, 27));
    deljButton1.setMinimumSize(new java.awt.Dimension(44, 27));
    deljButton1.setPreferredSize(new java.awt.Dimension(44, 27));
    deljButton1.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        deljButton1ActionPerformed(evt);
      }
    });

    addjButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gui/add.png"))); // NOI18N
    addjButton1.setMaximumSize(new java.awt.Dimension(44, 27));
    addjButton1.setMinimumSize(new java.awt.Dimension(44, 27));
    addjButton1.setPreferredSize(new java.awt.Dimension(44, 27));
    addjButton1.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        addjButton1ActionPerformed(evt);
      }
    });

    obraSocialjTextField.setText("Ingrese la obra social");
    obraSocialjTextField.setMaximumSize(new java.awt.Dimension(205, 27));
    obraSocialjTextField.setMinimumSize(new java.awt.Dimension(205, 27));
    obraSocialjTextField.setPreferredSize(new java.awt.Dimension(205, 27));
    obraSocialjTextField.addFocusListener(new java.awt.event.FocusAdapter() {
      public void focusGained(java.awt.event.FocusEvent evt) {
        obraSocialjTextFieldFocusGained(evt);
      }
    });
    obraSocialjTextField.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        obraSocialjTextFieldActionPerformed(evt);
      }
    });

    deljButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gui/remove.png"))); // NOI18N
    deljButton.setMaximumSize(new java.awt.Dimension(44, 27));
    deljButton.setMinimumSize(new java.awt.Dimension(44, 27));
    deljButton.setPreferredSize(new java.awt.Dimension(44, 27));
    deljButton.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        deljButtonActionPerformed(evt);
      }
    });

    javax.swing.GroupLayout obraSocialAndPlanjPanelLayout = new javax.swing.GroupLayout(obraSocialAndPlanjPanel);
    obraSocialAndPlanjPanel.setLayout(obraSocialAndPlanjPanelLayout);
    obraSocialAndPlanjPanelLayout.setHorizontalGroup(
      obraSocialAndPlanjPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(obraSocialAndPlanjPanelLayout.createSequentialGroup()
        .addContainerGap()
        .addGroup(obraSocialAndPlanjPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
          .addComponent(obraSocialjScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
          .addGroup(obraSocialAndPlanjPanelLayout.createSequentialGroup()
            .addComponent(obraSocialjTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 220, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(addjButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(deljButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addGroup(obraSocialAndPlanjPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
          .addGroup(obraSocialAndPlanjPanelLayout.createSequentialGroup()
            .addComponent(planjTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 220, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(addjButton1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(deljButton1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
          .addComponent(planjScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 320, javax.swing.GroupLayout.PREFERRED_SIZE))
        .addGap(6, 6, 6))
    );
    obraSocialAndPlanjPanelLayout.setVerticalGroup(
      obraSocialAndPlanjPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(obraSocialAndPlanjPanelLayout.createSequentialGroup()
        .addContainerGap()
        .addGroup(obraSocialAndPlanjPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
          .addComponent(planjScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
          .addComponent(obraSocialjScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addGroup(obraSocialAndPlanjPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          .addComponent(obraSocialjTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(planjTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(addjButton1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(deljButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(deljButton1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(addjButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        .addContainerGap())
    );

    jTabbedPane1.addTab("Obra Social", obraSocialAndPlanjPanel);

    nombrejLabel.setText("Nombre");

    apellidojLabel.setText("Apellido");

    telefonojLabel.setText("Teléfono");

    emailjLabel.setText("Email");

    guardarContactojButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gui/save.png"))); // NOI18N
    guardarContactojButton.setText("Guardar datos del contacto");
    guardarContactojButton.setEnabled(false);
    guardarContactojButton.setMaximumSize(new java.awt.Dimension(342, 27));
    guardarContactojButton.setMinimumSize(new java.awt.Dimension(342, 27));
    guardarContactojButton.setPreferredSize(new java.awt.Dimension(342, 27));
    guardarContactojButton.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        guardarContactojButtonActionPerformed(evt);
      }
    });

    modificarContactojButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gui/modificar.png"))); // NOI18N
    modificarContactojButton.setText("Modificar contacto");
    modificarContactojButton.setMaximumSize(new java.awt.Dimension(342, 27));
    modificarContactojButton.setMinimumSize(new java.awt.Dimension(342, 27));
    modificarContactojButton.setPreferredSize(new java.awt.Dimension(342, 27));
    modificarContactojButton.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        modificarContactojButtonActionPerformed(evt);
      }
    });

    cancelarGuardarContactojButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gui/cancelar.png"))); // NOI18N
    cancelarGuardarContactojButton.setText("Cancelar");
    cancelarGuardarContactojButton.setEnabled(false);
    cancelarGuardarContactojButton.setMaximumSize(new java.awt.Dimension(342, 27));
    cancelarGuardarContactojButton.setMinimumSize(new java.awt.Dimension(342, 27));
    cancelarGuardarContactojButton.setPreferredSize(new java.awt.Dimension(342, 27));
    cancelarGuardarContactojButton.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        cancelarGuardarContactojButtonActionPerformed(evt);
      }
    });

    javax.swing.GroupLayout contactojPanelLayout = new javax.swing.GroupLayout(contactojPanel);
    contactojPanel.setLayout(contactojPanelLayout);
    contactojPanelLayout.setHorizontalGroup(
      contactojPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(contactojPanelLayout.createSequentialGroup()
        .addGap(128, 128, 128)
        .addGroup(contactojPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          .addComponent(emailjLabel, javax.swing.GroupLayout.Alignment.TRAILING)
          .addComponent(telefonojLabel, javax.swing.GroupLayout.Alignment.TRAILING)
          .addComponent(apellidojLabel, javax.swing.GroupLayout.Alignment.TRAILING)
          .addComponent(nombrejLabel, javax.swing.GroupLayout.Alignment.TRAILING))
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addGroup(contactojPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
          .addComponent(telefonojTextField)
          .addComponent(emailjTextField, javax.swing.GroupLayout.Alignment.TRAILING)
          .addComponent(apellidojTextField)
          .addComponent(nombrejTextField)
          .addComponent(modificarContactojButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(guardarContactojButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(cancelarGuardarContactojButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        .addGap(128, 128, 128))
    );
    contactojPanelLayout.setVerticalGroup(
      contactojPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(contactojPanelLayout.createSequentialGroup()
        .addGap(64, 64, 64)
        .addGroup(contactojPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
          .addComponent(nombrejTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(nombrejLabel))
        .addGap(12, 12, 12)
        .addGroup(contactojPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
          .addComponent(apellidojTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(apellidojLabel))
        .addGap(12, 12, 12)
        .addGroup(contactojPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
          .addComponent(telefonojTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(telefonojLabel))
        .addGap(12, 12, 12)
        .addGroup(contactojPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
          .addComponent(emailjTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(emailjLabel))
        .addGap(88, 88, 88)
        .addComponent(modificarContactojButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(guardarContactojButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(cancelarGuardarContactojButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        .addContainerGap(56, Short.MAX_VALUE))
    );

    jTabbedPane1.addTab("Datos de Contacto", contactojPanel);

    addjButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gui/add.png"))); // NOI18N
    addjButton2.setMaximumSize(new java.awt.Dimension(44, 27));
    addjButton2.setMinimumSize(new java.awt.Dimension(44, 27));
    addjButton2.setPreferredSize(new java.awt.Dimension(44, 27));
    addjButton2.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        addjButton2ActionPerformed(evt);
      }
    });

    especialidadjTable.setModel(new javax.swing.table.DefaultTableModel(
      new Object [][] {

      },
      new String [] {
        "Especialidad", "Tarifa"
      }
    ) {
      Class[] types = new Class [] {
        java.lang.String.class, java.lang.Double.class
      };
      boolean[] canEdit = new boolean [] {
        false, false
      };

      public Class getColumnClass(int columnIndex) {
        return types [columnIndex];
      }

      public boolean isCellEditable(int rowIndex, int columnIndex) {
        return canEdit [columnIndex];
      }
    });
    especialidadjTable.getTableHeader().setReorderingAllowed(false);
    especialidadjTable.addMouseListener(new java.awt.event.MouseAdapter() {
      public void mouseClicked(java.awt.event.MouseEvent evt) {
        especialidadjTableMouseClicked(evt);
      }
    });
    especialidadjScrollPane.setViewportView(especialidadjTable);

    especialidadjTextField.setText("Ingrese la especialidad");
    especialidadjTextField.setMaximumSize(new java.awt.Dimension(220, 27));
    especialidadjTextField.setMinimumSize(new java.awt.Dimension(220, 27));
    especialidadjTextField.setPreferredSize(new java.awt.Dimension(220, 27));
    especialidadjTextField.addFocusListener(new java.awt.event.FocusAdapter() {
      public void focusGained(java.awt.event.FocusEvent evt) {
        especialidadjTextFieldFocusGained(evt);
      }
    });
    especialidadjTextField.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        especialidadjTextFieldActionPerformed(evt);
      }
    });

    deljButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gui/remove.png"))); // NOI18N
    deljButton2.setMaximumSize(new java.awt.Dimension(44, 27));
    deljButton2.setMinimumSize(new java.awt.Dimension(44, 27));
    deljButton2.setPreferredSize(new java.awt.Dimension(44, 27));
    deljButton2.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        deljButton2ActionPerformed(evt);
      }
    });

    actualizarTarifasjButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gui/defaults.png"))); // NOI18N
    actualizarTarifasjButton.setText("Actualizar tarifas");
    actualizarTarifasjButton.setMaximumSize(new java.awt.Dimension(220, 27));
    actualizarTarifasjButton.setMinimumSize(new java.awt.Dimension(220, 27));
    actualizarTarifasjButton.setPreferredSize(new java.awt.Dimension(220, 27));
    actualizarTarifasjButton.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        actualizarTarifasjButtonActionPerformed(evt);
      }
    });

    javax.swing.GroupLayout tarifajPanelLayout = new javax.swing.GroupLayout(tarifajPanel);
    tarifajPanel.setLayout(tarifajPanelLayout);
    tarifajPanelLayout.setHorizontalGroup(
      tarifajPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(tarifajPanelLayout.createSequentialGroup()
        .addGap(100, 100, 100)
        .addGroup(tarifajPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          .addComponent(actualizarTarifasjButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addGroup(tarifajPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
            .addGroup(tarifajPanelLayout.createSequentialGroup()
              .addComponent(especialidadjTextField, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
              .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
              .addComponent(addjButton2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
              .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
              .addComponent(deljButton2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addComponent(especialidadjScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 458, javax.swing.GroupLayout.PREFERRED_SIZE)))
        .addContainerGap(100, Short.MAX_VALUE))
    );
    tarifajPanelLayout.setVerticalGroup(
      tarifajPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(tarifajPanelLayout.createSequentialGroup()
        .addGap(12, 12, 12)
        .addComponent(actualizarTarifasjButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
        .addComponent(especialidadjScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 355, Short.MAX_VALUE)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addGroup(tarifajPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          .addComponent(especialidadjTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(addjButton2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(deljButton2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        .addContainerGap())
    );

    jTabbedPane1.addTab("Tarifario", tarifajPanel);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
    this.setLayout(layout);
    layout.setHorizontalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(layout.createSequentialGroup()
        .addGap(0, 0, 0)
        .addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        .addGap(0, 0, 0))
    );
    layout.setVerticalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(layout.createSequentialGroup()
        .addContainerGap()
        .addComponent(jTabbedPane1))
    );
  }// </editor-fold>//GEN-END:initComponents

  private void obraSocialjTextFieldFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_obraSocialjTextFieldFocusGained
    obraSocialjTextField.selectAll();
  }//GEN-LAST:event_obraSocialjTextFieldFocusGained

  private void planjTextFieldFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_planjTextFieldFocusGained
    planjTextField.selectAll();
  }//GEN-LAST:event_planjTextFieldFocusGained

  private void addjButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addjButtonActionPerformed
    if (InputHelper.isNonAlphanumeric(obraSocialjTextField.getText())) {
      JOptionPane.showMessageDialog(this, "Nombre de la obra social inválido. Sólo se permiten letras y números para el nombre de la obra social.", "Atención!", JOptionPane.WARNING_MESSAGE);
      return;
    }

    try {
      ObraSocial obraSocial = new ObraSocial(-1, obraSocialjTextField.getText(), "", "", "", "");
      obraSocial.Save();
      Tarifa.CreateTarifasForObraSocial(obraSocial.getId());

      obraSocialSeleccionada = obraSocial;
      obraSocialjTextField.setText("");

      int ans = JOptionPane.showConfirmDialog(
         this,
           String.format("Se creó exitosamente la obra social %s.\nDesea actualizar las tarifas ahora?", obraSocialSeleccionada.getNombre()),
           "Nueva obra social creada: DEBE ACTUALIZAR LAS TARIFAS",
         JOptionPane.YES_NO_OPTION
       );

       if (ans == JOptionPane.YES_OPTION) {
         jTabbedPane1.setSelectedIndex(2);
       }

      updateObraSocialTable(ObraSocial.All());
      int sel = oIDs.indexOf(obraSocialSeleccionada.getId());
      obraSocialjTable.setRowSelectionInterval(sel, sel);
      obraSocialjTableMouseClicked(null);
    } catch (SQLException e) {
      System.out.printf("?add issue\n");
    }
  }//GEN-LAST:event_addjButtonActionPerformed

  private void deljButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deljButtonActionPerformed
    if (obraSocialSeleccionada.getId() == 0) {
      JOptionPane.showMessageDialog(this, "No es posible eliminar el tipo de atención particular.\nLas atenciones particulares son esenciales para el correcto funcionamiento del sistema.", "ERROR!", JOptionPane.ERROR_MESSAGE);
      return;
    }

    if (obraSocialSeleccionada == null) {
      JOptionPane.showMessageDialog(this, "No seleccionó ninguna obra social. Seleccione una obra social, por favor.", "Atención!", JOptionPane.WARNING_MESSAGE);
      return;
    }

    int ans = JOptionPane.showConfirmDialog(
      this,
      "Eliminar la obra social " + obraSocialSeleccionada.getNombre() + "?",
      "Desea eliminar la obra social seleccionada?",
      JOptionPane.YES_NO_OPTION
    );

    if (ans == JOptionPane.NO_OPTION) {
      return;
    }

    String err = obraSocialSeleccionada.Delete();
    if (err != null && err.equals(InputHelper.SQLForeignKey)) {
      JOptionPane.showMessageDialog(this, "No es posible eliminar esta obra social debido a que otros datos dependen de ella.", "ERROR!", JOptionPane.ERROR_MESSAGE);
      return;
    }

    obraSocialSeleccionada = null;
    preObraSocialAndPlan();
  }//GEN-LAST:event_deljButtonActionPerformed

  private void obraSocialjTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_obraSocialjTextFieldActionPerformed
    addjButtonActionPerformed(evt);
  }//GEN-LAST:event_obraSocialjTextFieldActionPerformed

  private void obraSocialjTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_obraSocialjTableMouseClicked
    // preinit
    int sel = obraSocialjTable.getSelectedRow();
    if (sel == -1) {
      return;
    }

    int id = oIDs.get(sel);
    try {
      obraSocialSeleccionada = new ObraSocial(ObraSocial.SearchByID(id));
      boolean particular = obraSocialSeleccionada.getId() == 0;
      updatePlanTable(ObraSocialPlan.All(obraSocialSeleccionada.getId()));
      jTabbedPane1.setEnabled(true);
      jTabbedPane1.setTitleAt(0, String.format("<html><b>%s</b></html>", !particular ? obraSocialSeleccionada.getNombre() : "Atenciones Particulares"));
      jTabbedPane1.setEnabledAt(1, !particular);
      try {
        planjTable.setRowSelectionInterval(0, 0);
        planSeleccionado = new ObraSocialPlan(ObraSocialPlan.SearchByID(pIDs.get(0)));
      } catch (Exception e) {
      }
    } catch (SQLException e) {
      System.out.printf("?u38soj\n");
    }
  }//GEN-LAST:event_obraSocialjTableMouseClicked

  private void jTabbedPane1StateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_jTabbedPane1StateChanged
    if (obraSocialSeleccionada == null) {
      setContactoEmpty();
      return;
    }

    boolean particular = obraSocialSeleccionada.getId() == 0;
    jTabbedPane1.setTitleAt(0, String.format("<html><b>%s</b></html>", !particular ? obraSocialSeleccionada.getNombre() : "Atenciones Particulares"));
    jTabbedPane1.setEnabledAt(1, !particular);
    if (particular) {
      setContactoEditable(false);
      modificarContactojButton.setEnabled(false);
    } else {
      modificarContactojButton.setEnabled(true);
    }

    setContactoData();
    try {
      updateEspecialidadTable(Especialidad.All());
    } catch (SQLException e) {
    }
    //especialidadjTableMouseClicked(null);
  }//GEN-LAST:event_jTabbedPane1StateChanged

  private void modificarContactojButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_modificarContactojButtonActionPerformed
    modificarContactojButton.setEnabled(false);
    jTabbedPane1.setEnabled(false);
    guardarContactojButton.setEnabled(true);
    cancelarGuardarContactojButton.setEnabled(true);
    setContactoEditable(true);
  }//GEN-LAST:event_modificarContactojButtonActionPerformed

  private void guardarContactojButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_guardarContactojButtonActionPerformed
    String nombre = nombrejTextField.getText();
    if (InputHelper.isNonAlphabetic(nombre)) {
      JOptionPane.showMessageDialog(this, "Nombre inválido. Ingrese correctamente el nombre del contacto, por favor.", "Atención!", JOptionPane.WARNING_MESSAGE);
      return;
    }

    String apellido = apellidojTextField.getText();
    if (InputHelper.isNonAlphabetic(apellido)) {
      JOptionPane.showMessageDialog(this, "Apellido inválido. Ingrese correctamente el apellido del contacto, por favor.", "Atención!", JOptionPane.WARNING_MESSAGE);
      return;
    }

    String telephone = telefonojTextField.getText();
    if (InputHelper.isNonValidPhone(telephone)) {
      JOptionPane.showMessageDialog(this, "Número de teléfono inválido. Ingrese correctamente el número de télefono del contacto, por favor.", "Atención!", JOptionPane.WARNING_MESSAGE);
      return;
    }

    String email = emailjTextField.getText();
    if (!InputHelper.isValidEmail(email)) {
      JOptionPane.showMessageDialog(this, "Email inválido. Ingrese correctamente el email del contacto, por favor.", "Atención!", JOptionPane.WARNING_MESSAGE);
      return;
    }

    try {
      ObraSocialDTO dto = new ObraSocialDTO(obraSocialSeleccionada.getId(), obraSocialSeleccionada.getNombre(), nombre, apellido, telephone, email);
      ObraSocial o = new ObraSocial(dto);
      o.UpdateContacto();
      JOptionPane.showMessageDialog(
        this,
        String.format("Se actualizaron correctamente los datos del contacto de %s.", obraSocialSeleccionada.getNombre()),
        "Éxito: Datos del contacto actualizados",
        JOptionPane.INFORMATION_MESSAGE
      );
    } catch (SQLException e) {
      System.out.printf("?updating contacto issue\n");
    }

    modificarContactojButton.setEnabled(true);
    jTabbedPane1.setEnabled(true);
    guardarContactojButton.setEnabled(false);
    cancelarGuardarContactojButton.setEnabled(false);
    setContactoEditable(false);
  }//GEN-LAST:event_guardarContactojButtonActionPerformed

  private void obraSocialjTableKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_obraSocialjTableKeyReleased
    obraSocialjTableMouseClicked(null);
  }//GEN-LAST:event_obraSocialjTableKeyReleased

  private void especialidadjTextFieldFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_especialidadjTextFieldFocusGained
    especialidadjTextField.selectAll();
  }//GEN-LAST:event_especialidadjTextFieldFocusGained

  private void addjButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addjButton2ActionPerformed
    if (InputHelper.isNonAlphabetic(especialidadjTextField.getText())) {
      JOptionPane.showMessageDialog(this, "Nombre de la especialidad inválido. Sólo se permiten letras para el nombre de la especialidad médica.", "Atención!", JOptionPane.WARNING_MESSAGE);
      return;
    }

    try {
      Especialidad especialidad = new Especialidad(-1, especialidadjTextField.getText());
      especialidad.Save();
      Tarifa.CreateTarifasForEspecialidad(especialidad.getId());

      especialidadSeleccionada = especialidad;
      especialidadjTextField.setText("");

      JOptionPane.showMessageDialog(
        this,
        "Se creó exitosamente la nueva especialidad. Recuerde actualizar las tarifas de todas las obras sociales.",
        "Éxito: Nueva especialidad creada",
        JOptionPane.INFORMATION_MESSAGE
      );

      updateEspecialidadTable(Especialidad.All());
      int sel = eIDs.indexOf(especialidadSeleccionada.getId());
      especialidadjTable.setRowSelectionInterval(sel, sel);
      especialidadjTableMouseClicked(null);
    } catch (SQLException e) {
      System.out.printf("?add issue\n");
    }
  }//GEN-LAST:event_addjButton2ActionPerformed

  private void especialidadjTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_especialidadjTableMouseClicked
    // preinit
    int sel = especialidadjTable.getSelectedRow();
    if (sel == -1 || obraSocialSeleccionada == null) {
      return;
    }

    int id = eIDs.get(sel);
    try {
      especialidadSeleccionada = new Especialidad(Especialidad.SearchByID(id));
      TarifaDTO t = Tarifa.SearchByObraSocialEspecialidad(obraSocialSeleccionada.getId(), especialidadSeleccionada.getId());
      //tarifajTextField.setEditable(false);
      //tarifajTextField.setText(String.valueOf(t.getPrecio()));
    } catch (SQLException e) {
      System.out.printf("?298720oj\n");
    }
  }//GEN-LAST:event_especialidadjTableMouseClicked

  private void especialidadjTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_especialidadjTextFieldActionPerformed
    addjButton2ActionPerformed(evt);
  }//GEN-LAST:event_especialidadjTextFieldActionPerformed

  private void deljButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deljButton2ActionPerformed
    if (especialidadSeleccionada == null) {
      JOptionPane.showMessageDialog(this, "No seleccionó ninguna especialidad. Seleccione una especialidad médica, por favor.", "Atención!", JOptionPane.WARNING_MESSAGE);
      return;
    }

    int ans = JOptionPane.showConfirmDialog(
      this,
      "Eliminar la especialidad " + especialidadSeleccionada.getNombre() + "?",
      "Desea eliminar la especialidad médica seleccionada?",
      JOptionPane.YES_NO_OPTION
    );

    if (ans == JOptionPane.NO_OPTION) {
      return;
    }

    String err = especialidadSeleccionada.Delete();
    if (err != null && err.equals(InputHelper.SQLForeignKey)) {
      JOptionPane.showMessageDialog(this, "No es posible eliminar esta especialidad debido a que otros datos dependen de la misma.", "ERROR!", JOptionPane.ERROR_MESSAGE);
      return;
    }

    especialidadSeleccionada = null;
    preEspecialidad();
  }//GEN-LAST:event_deljButton2ActionPerformed

  private void actualizarTarifasjButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_actualizarTarifasjButtonActionPerformed
    int j = 0;

    try {

      for (int i : tIDs) {
        TarifaDTO dto = Tarifa.SearchByID(i);
        Tarifa t = new Tarifa(dto);
        t.EditPrecio(Double.parseDouble(especialidadjTable.getModel().getValueAt(j++, 1).toString()));
      }

      JOptionPane.showMessageDialog(this, String.format("Se actualizaron exitosamente las tarifas de %s.", obraSocialSeleccionada.getNombre()), "Éxito: Tarifario actualizado", JOptionPane.INFORMATION_MESSAGE);

    } catch (Exception e) {
      JOptionPane.showMessageDialog(this, "No es posible actualizar las tarifas.\nSólo se permiten valores númericos en las tarifas.", "ERROR!", JOptionPane.ERROR_MESSAGE);
      try {
        updateEspecialidadTable(Especialidad.All());
      } catch (Exception ex) {
      }
    }

    especialidadjTableMouseClicked(null);
  }//GEN-LAST:event_actualizarTarifasjButtonActionPerformed

  private void deljButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deljButton1ActionPerformed
    if (planSeleccionado.getId() == 0) {
      JOptionPane.showMessageDialog(this, "No es posible eliminar el tipo de atención particular.\nLas atenciones particulares son esenciales para el correcto funcionamiento del sistema.", "ERROR!", JOptionPane.ERROR_MESSAGE);
      return;
    }

    if (planSeleccionado == null) {
      JOptionPane.showMessageDialog(this, "No seleccionó ningún plan. Seleccione un plan, por favor.", "Atención!", JOptionPane.WARNING_MESSAGE);
      return;
    }

    int ans = JOptionPane.showConfirmDialog(
      this,
      "Eliminar el plan " + planSeleccionado.getNombre() + "?",
      "Desea eliminar el plan seleccionado?",
      JOptionPane.YES_NO_OPTION
    );

    if (ans == JOptionPane.NO_OPTION) {
      return;
    }

    String err = planSeleccionado.Delete();
    if (err != null && err.equals(InputHelper.SQLForeignKey)) {
      JOptionPane.showMessageDialog(this, "No es posible eliminar este plan debido a que otros datos dependen del mismo.", "ERROR!", JOptionPane.ERROR_MESSAGE);
      return;
    }

    planSeleccionado = null;
    try {
      updatePlanTable(ObraSocialPlan.All(obraSocialSeleccionada.getId()));
      try {
        planjTable.setRowSelectionInterval(0, 0);
        planSeleccionado = new ObraSocialPlan(ObraSocialPlan.SearchByID(pIDs.get(0)));
      } catch (Exception e) {
      }
    } catch (SQLException e) {
      System.out.printf("?s2382skd\n");
    }
  }//GEN-LAST:event_deljButton1ActionPerformed

  private void planjTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_planjTableMouseClicked
    // preinit
    int sel = planjTable.getSelectedRow();
    if (sel == -1) {
      return;
    }

    int id = pIDs.get(sel);
    try {
      planSeleccionado = new ObraSocialPlan(ObraSocialPlan.SearchByID(id));
    } catch (SQLException e) {
      System.out.printf("?u222l338soj\n");
    }
  }//GEN-LAST:event_planjTableMouseClicked

  private void addjButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addjButton1ActionPerformed
    if (obraSocialSeleccionada.getId() == 0) {
      JOptionPane.showMessageDialog(this, "No es posible modificar el tipo de atención particular.\nLas atenciones particulares no tienen planes asociados.", "ERROR!", JOptionPane.ERROR_MESSAGE);
      return;
    }

    if (InputHelper.isNonAlphanumeric(planjTextField.getText())) {
      JOptionPane.showMessageDialog(this, "Nombre del plan inválido. Sólo se permiten letras y números para el nombre del plan.", "Atención!", JOptionPane.WARNING_MESSAGE);
      return;
    }

    try {
      ObraSocialPlan obraSocialPlan = new ObraSocialPlan(-1, obraSocialSeleccionada.getId(), planjTextField.getText());
      obraSocialPlan.Save();

      planSeleccionado = obraSocialPlan;
      planjTextField.setText("");

      JOptionPane.showMessageDialog(
        this,
        String.format("Se creó exitosamente el plan %s.", planSeleccionado.getNombre()),
        "Éxito: Nuevo plan creado",
        JOptionPane.INFORMATION_MESSAGE
      );

      updatePlanTable(ObraSocialPlan.All(obraSocialSeleccionada.getId()));
      int sel = pIDs.indexOf(planSeleccionado.getId());
      planjTable.setRowSelectionInterval(sel, sel);
    } catch (SQLException e) {
      System.out.printf("?add1 issue\n");
    }
  }//GEN-LAST:event_addjButton1ActionPerformed

  private void planjTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_planjTextFieldActionPerformed
    addjButton1ActionPerformed(evt);
  }//GEN-LAST:event_planjTextFieldActionPerformed

  private void cancelarGuardarContactojButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelarGuardarContactojButtonActionPerformed
    modificarContactojButton.setEnabled(true);
    jTabbedPane1.setEnabled(true);
    guardarContactojButton.setEnabled(false);
    cancelarGuardarContactojButton.setEnabled(false);
    setContactoData();
    setContactoEditable(false);
  }//GEN-LAST:event_cancelarGuardarContactojButtonActionPerformed

  // Variables declaration - do not modify//GEN-BEGIN:variables
  private javax.swing.JButton actualizarTarifasjButton;
  private javax.swing.JButton addjButton;
  private javax.swing.JButton addjButton1;
  private javax.swing.JButton addjButton2;
  private javax.swing.JLabel apellidojLabel;
  private javax.swing.JTextField apellidojTextField;
  private javax.swing.JButton cancelarGuardarContactojButton;
  private javax.swing.JPanel contactojPanel;
  private javax.swing.JButton deljButton;
  private javax.swing.JButton deljButton1;
  private javax.swing.JButton deljButton2;
  private javax.swing.JLabel emailjLabel;
  private javax.swing.JTextField emailjTextField;
  private javax.swing.JScrollPane especialidadjScrollPane;
  private javax.swing.JTable especialidadjTable;
  private javax.swing.JTextField especialidadjTextField;
  private javax.swing.JButton guardarContactojButton;
  private javax.swing.JTabbedPane jTabbedPane1;
  private javax.swing.JButton modificarContactojButton;
  private javax.swing.JLabel nombrejLabel;
  private javax.swing.JTextField nombrejTextField;
  private javax.swing.JPanel obraSocialAndPlanjPanel;
  private javax.swing.JScrollPane obraSocialjScrollPane;
  private javax.swing.JTable obraSocialjTable;
  private javax.swing.JTextField obraSocialjTextField;
  private javax.swing.JScrollPane planjScrollPane;
  private javax.swing.JTable planjTable;
  private javax.swing.JTextField planjTextField;
  private javax.swing.JPanel tarifajPanel;
  private javax.swing.JLabel telefonojLabel;
  private javax.swing.JTextField telefonojTextField;
  // End of variables declaration//GEN-END:variables
}
